<template>
    <div class="history">
        <div class="crumbs">
            <el-breadcrumb separator-class="el-icon-arrow-right">
                <el-breadcrumb-item> <i class="el-icon-folder" style="margin-right:10px"></i>项目部管理 </el-breadcrumb-item>
                <el-breadcrumb-item>历史项目</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <!-- <el-button
                    type="primary"
                    icon="el-icon-delete"
                    class="handle-del mr10"
                    @click="delAllSelection"
                >批量删除</el-button>-->

                <div class="title">历史项目</div>

                <div>
                    <el-button type="primary" class="titleBtn1" style="width:60px;" @click="tableToExcel">导出</el-button>
                </div>

                <div class="prjectName mr20" style="padding-left:40px">
                    <span class="name">项目名称</span>
                    <el-input class="handle-select mr10" placeholder="请输入" v-model="query.projectname"></el-input>
                </div>
                <div class="prjectName mr20">
                    <span class="name">项目类型</span>
                    <el-cascader
                        class="handle-select mr10"
                        v-model="category"
                        :options="options"
                        :props="{ expandTrigger: 'hover' }"
                        @change="handleChange"
                    ></el-cascader>
                </div>
                <div class="department mr0">
                    <span class="name">所属事业部</span>
                    <el-select v-model="value1" placeholder="请选择" @change="getSelectedDep" class="handle-select mr10">
                        <el-option v-for="item in depOptions" :key="item.deptid" :label="item.deptname" :value="item.deptid"></el-option>
                    </el-select>
                </div>
                <div class="stateTime mr20">
                    <span class="name">开始时间</span>
                    <el-date-picker
                        class="handle-select"
                        v-model="query.startdate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择"
                    ></el-date-picker>
                </div>
                <div class="stateTime mr20">
                    <span class="name">结束时间</span>
                    <el-date-picker
                        class="handle-select"
                        v-model="query.enddate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择"
                    ></el-date-picker>
                </div>
                <div class="searchBox">
                    <!-- <el-input v-model="query.name" placeholder="用户名" class="handle-input mr10"></el-input> -->
                    <el-button class="titleBtn" type="primary" style="width:60px;" @click="handleSearch">查询</el-button>
                    <el-button class="titleBtn1" type="primary" style="width:60px" @click="reset">重置</el-button>
                </div>
            </div>

            <el-table :data="tableData" border stripe class="table" ref="multipleTable" header-cell-class-name="table-header">
                <!-- <el-table-column type="selection" width="55" align="center"></el-table-column> -->
                <!-- <el-table-column prop="id" label="序号" width="55" align="center"></el-table-column> -->
                <el-table-column show-overflow-tooltip label="序号" width="55" align="center">
                    <template slot-scope="scope">{{ scope.$index + 1 }}</template>
                </el-table-column>
                <el-table-column prop="projectid" label="项目ID" :show-overflow-tooltip="true" align="center"></el-table-column>
                <el-table-column
                    prop="projectname"
                    label="项目名称"
                    width="150px"
                    :show-overflow-tooltip="true"
                    align="center"
                ></el-table-column>
                <!-- <el-table-column prop="password" label="登录密码">******</el-table-column> -->
                <el-table-column show-overflow-tooltip label="合同总产值" align="center">
                    <template slot-scope="scope">{{ scope.row.contractvalue }}万</template>
                </el-table-column>
                <el-table-column prop="deptname" label="所属事业部" :show-overflow-tooltip="true" align="center"></el-table-column>
                <el-table-column prop="startdate" label="开工时间" align="center" show-overflow-tooltip></el-table-column>
                <el-table-column prop="period" label="工期" align="center" show-overflow-tooltip>
                    <template slot-scope="scope">{{ scope.row.period }}个月</template>
                </el-table-column>
                <el-table-column prop="userid" label="关联用户ID" align="center" show-overflow-tooltip></el-table-column>
                <el-table-column prop="category" label="项目类型" :show-overflow-tooltip="true" align="center"></el-table-column>
                <el-table-column prop="region" label="区域(省)" align="center" show-overflow-tooltip></el-table-column>
                <el-table-column prop="state" label="实施状态" :formatter="isState" align="center" show-overflow-tooltip></el-table-column>
                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                        <el-button type="text" @click="handleDetail(scope.$index, scope.row)">详细信息</el-button>
                        <!-- <el-button type="text"  @click="handleDelete(scope.$index, scope.row)"
                            >细化分解表</el-button
                        >-->
                    </template>
                </el-table-column>
            </el-table>
            <div class="table-data_statistic">
              <el-form inline label-width="120px">
                <el-form-item label="总计:"  label-width="60px"></el-form-item>
                <el-form-item label="项目总数:">{{tableDataStatistic.projectNum}}个</el-form-item>
                <el-form-item label="合同总额:">{{tableDataStatistic.totalContractValue}}万元</el-form-item>
                <el-form-item label="当月完成产值:">{{tableDataStatistic.monthValue}}万元</el-form-item>
                <el-form-item label="累积完成产值:">{{tableDataStatistic.totalValue}}万元</el-form-item>
                <el-form-item label="剩余合同额:">{{tableDataStatistic.surplusContractValue}}万元</el-form-item>
              </el-form>
            </div>
            <div class="pagination">
                <el-pagination
                    background
                    layout=" prev, pager, next"
                    :current-page="query.page"
                    :page-size="pageSize"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 点击详细信息 -->
        <el-dialog title="项目详情" :visible.sync="projectDetailVisible" width="70%" custom-class="output" :lock-scroll="false">
            <div class="tableBox">
                <table id="table">
                    <thead>
                        <tr>
                            <th class="tableTitle m1">序号</th>
                            <th class="tableTitle" style="width:120px">分项内容</th>
                            <th class="tableTitle">上报时间</th>
                            <th class="tableTitle">上次完成工作量</th>
                            <th class="tableTitle">合同单价(元)</th>
                            <th class="tableTitle">当月完成产值(元)</th>
                            <th class="tableTitle">当月完成工作量</th>
                            <th class="tableTitle">累计完成产值(元)</th>
                            <th class="tableTitle">完成进度</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(item, index) in stu" :class="index % 2 == 0 ? 'tr1' : 'tr2'" :key="index">
                            <td style="text-align:center">{{ item.orderNo }}</td>
                            <td
                                class="tdItem"
                                style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis;"
                            >
                                {{ item.subitem }}
                            </td>
                            <td class="tdItem">{{ item.reportTime }}</td>
                            <td class="tdItem">{{ item.prevCompleted }}</td>
                            <td class="tdItem">{{ item.price }}</td>
                            <td class="tdItem">{{ item.monthCompletedValue }}</td>
                            <td class="tdItem">{{ item.monthCompleted }}</td>
                            <td class="tdItem">{{ item.totalCompletedValue }}</td>
                            <td class="tdItem tdItem1">
                                <el-progress
                                    :color="customColors"
                                    :stroke-width="15"
                                    :percentage="Number((item.totalCompletedValue * 100) / (item.price * item.quantity)).toFixed(0)"
                                ></el-progress>
                            </td>
                        </tr>
                    </tbody>
                </table>
                <div class="progress">
                  <span style="margin-right:64px;">总进度</span>
                  <el-progress class="progress-width" :color="customColors" :stroke-width="15" :percentage="Number(percentage).toFixed(0)"></el-progress>
                  <span>总计完成产值：{{projectDetailOutputValue|toTenThousand}}</span>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { getProjectList, specifyList, findDepList, findAll, allCategory } from '../../api/index';
export default {
    name: 'basetable',
    data() {
        /**
         * tableDataStatistic:表格统计数据
         */
        return {
            category: '', //分类
            query: {
                state: 2,
                projectname: '',
                deptid: '',
                startdate: '',
                enddate:'',
                //  pageSize: 10,
                page: 1,
                classifyId: '',
                categoryId: ''
            },
            pageTotal: 0,
            pageSize: 10,
            value1: '',
            percentage: '', //总进度

            //用户搜索条件
            querySearch: {
                state: 2,
                projectname: '',
                deptid: '',
                startdate: ''
            },
            stu: [],
            customColors: [
                { color: '#7ED321', percentage: 60 },
                { color: '#F5A623', percentage: 90 },
                { color: '#D0021B', percentage: 99 },
                { color: '#3585D9', percentage: 100 }
            ],
            tableData: [],
            tableData1: [],
            multipleSelection: [],
            delList: [],
            projectDetailVisible: false,

            // form: {},
            idx: -1,
            id: -1,
            totals: '',
            depOptions: [] ,//事业部列表
            tableDataStatistic: {
              monthValue: null,
              projectNum: null,
              surplusContractValue: null,
              totalContractValue: null,
              totalValue: null
            },
            projectDetailOutputValue: 0
        };
    },
    created() {
        this.getData();
        this.getDepList();
        this.getAllCategory();
    },
    filters: {
      // 转换为万元
      toTenThousand: function(value) {
        if(value > 10000) {
          return (value/10000).toFixed(2) + '万元'
        } else {
          return value.toFixed(2) + '元'
        }
      }
    },
    methods: {
        // 获取历史项目列表
        getData() {
            if (localStorage.getItem('deptid') !== 'null') {
                this.query.deptid = localStorage.getItem('deptid');
            }
            getProjectList(this.query).then(res => {
                // console.log(res.result)
                if (res.code === 200) {
                    this.tableData = res.result.projectList;
                    this.query.page = res.result.pageInfo.current;
                    this.pageTotal = res.result.pageInfo.total;
                    // 获取统计数据
                    for(const i in this.tableDataStatistic) {
                      this.tableDataStatistic[i] = res.result[i] || 0
                    }
                } else {
                    this.tableData = [];
                }
            });
        },
        getAllData() {
            findAll(this.query).then(res => {
                if (res.code === 200) {
                    this.tableData1 = res.result.projectList;
                    this.getdaochu();
                } else {
                    this.$message.error(res.message);
                }
            });
        },
        //获取事业部项目列表
        getDepList() {
            findDepList().then(res => {
                //    console.log(res)
                if (res.code === 200) {
                    if (localStorage.getItem('deptid') !== 'null') {
                        this.depOptions = res.result.filter(res => {
                            return res.deptid == localStorage.getItem('deptid');
                        });
                        this.value1 = this.depOptions[0].deptname;
                    } else {
                        this.depOptions = res.result;
                    }
                }
            });
        },
        //格式化实施状态
        isState(scope) {
            if (scope.state === 0) {
                return '未开始';
            } else if (scope.state === 1) {
                return '进行中';
            } else {
                return '已完成';
            }
            // return scope.state;
        },
        //获取选中的key
        getSelectedDep(item) {
            this.query.deptid = item;
        },
        // 触发搜索按钮
        handleSearch() {
            this.query.page = 1;
            if (localStorage.getItem('deptid') !== 'null') {
                this.query.deptid = localStorage.getItem('deptid');
            }
            getProjectList(this.query).then(res => {
                // console.log(res.result)
                if (res.code === 200) {
                    this.tableData = res.result.projectList;
                    this.query.page = res.result.pageInfo.current;
                    this.pageTotal = res.result.pageInfo.total;
                    // 获取统计数据
                    for(const i in this.tableDataStatistic) {
                      this.tableDataStatistic[i] = res.result[i] || 0
                    }
                } else {
                    this.tableData = [];
                }
            });
        },
        // 删除操作
        handleDelete(index, row) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    this.$message.success('删除成功');
                    this.tableData.splice(index, 1);
                })
                .catch(() => {});
        },

        //获取某一项目的详细信息
        getProjectDetail() {},
        //点击详细信息
        handleDetail(index, row) {
            this.totals = row.contractvalue * 10000;
            this.idx = index;
            this.form = row;
            specifyList({ projectid: this.form.projectid }).then(res => {
                console.log(res);
                if (res.code == 200) {
                    this.stu = res.result.specifyList;
                    this.projectDetailOutputValue = this.stu.reduce((total,current) =>total+current.totalCompletedValue, 0)
                }
                let a = res.result.specifyList.reduce((sum, cur) => {
                    return Number(cur.totalCompletedValue) + Number(sum);
                }, []);
                this.percentage = (a / this.totals) * 100;
            });

            this.projectDetailVisible = true;
        },
        // 保存编辑
        saveEdit() {
            this.editVisible = false;
            this.$message.success(`修改第 ${this.idx + 1} 行成功`);
            this.$set(this.tableData, this.idx, this.form);
        },
        // 分页导航
        handlePageChange(val) {
            // alert(val)
            this.query.page = val;
            this.getData();
        },
        //点击重置
        reset() {
            (this.query = {
                state: 2,
                projectname: '',
                deptid: '',
                startdate: '',
                enddate:'',
                //  pageSize: 10,
                page: 1,
                classifyId: '',
                categoryId: ''
            }),
                (this.value1 = '');
            this.category = '';
            this.getData();
        },
        //点击导出
        tableToExcel() {
            //列标题
            this.getAllData();
        },
        //导出数据
        getdaochu() {
            this.tableData1.filter((item, index) => {
                item.id = index + 1;
                item.state = '已完成';
                item.period = item.period + '个月';
                item.deptid = `"${item.proSpecifyList.join(`\r\n`)}"`;
                item.reportstate = (Number(item.totalCompletedValue) / (Number(item.contractvalue) * 100)).toFixed(0) + '%';
                item.contractvalue = item.contractvalue + `万`;
                item.reportday = (item.totalCompletedValue / 10000).toFixed(2) + '万';
                item.totalCompletedValue = '';
                item.proSpecifyList = '';
                item.timeSchedule = '';
                // item.coefficient =0.2
                // Object.keys(item).forEach(key=>{
                //     if(!item[key]&&item[key]!==0){
                //         state=false
                //         return state
                //     }
                // })
            });
            console.log('tabData1' + this.tableData1);
            // 列标题，逗号隔开，每一个逗号就是隔开一个单元格
            let str = `序号,项目ID,项目名称,合同总产值,所属事业部,开工时间,工期,关联用户ID,区域(省),实施状态,项目类型,完成产值,完成进度,分项信息\n`;
            //增加\t为了不让表格显示科学计数法或者其他格式
            for (let i = 0; i < this.tableData1.length; i++) {
                for (let item in this.tableData1[i]) {
                    str += `${this.tableData1[i][item] + '\t'},`;
                }
                str += '\n';
            }
            //encodeURIComponent解决中文乱码
            let uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str);
            //通过创建a标签实现
            let link = document.createElement('a');
            link.href = uri;
            //对下载的文件命名
            link.download = '历史的项目数据表.csv';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        },
        //取所有项目的分类
        getAllCategory() {
            allCategory({}).then(res => {
                if (res.code == 200) {
                    this.options = res.result.classifyList;
                    this.options.filter((item, index) => {
                        item.value = item.id;
                        item.label = item.name;
                        item.children = item.categoryList;
                        item.children.filter((item, index) => {
                            item.value = item.id;
                            item.label = item.name;
                        });
                    });

                    console.log(this.options);
                } else {
                    this.$message.error(message);
                }
            });
        },
        //点击项目类型
        handleChange(value) {
            (this.query.classifyId = value[0]), (this.query.categoryId = value[1]);
            console.log(value);
        }
    }
};
</script>

<style scoped lang="scss">
.handle-box {
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    overflow: hidden;
}
.title {
    height: 28px;
    font-size: 20px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: rgba(51, 51, 51, 1);
    margin-right: 40px;
    min-width: 80px;
}
.titleBtn {
    background: rgba(33, 74, 143, 1);
    color: #fff;
    border: none;
    font-size: 16px;
    border-radius: 5px;
    height: 35px;
}
.titleBtn1 {
    background: rgba(0, 79, 171, 0.2);
    color: rgba(0, 79, 171, 1);
    border: none;
    font-size: 16px;
    border-radius: 5px;
    height: 35px;
}
.handle-box .name {
    margin-right: 10px;
}
.mr0{
    font-size: 14px;
    min-width: 234px;
}
.mr20 {
    font-size: 14px;
    // margin-right: 8px;
    min-width: 221px;
}
.handle-select {
    width: 140px;
}
.searchBox {
    min-width: 240px;
    margin-left: auto;
}
.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.title {
    float: left;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
.tableTitle {
    background: rgba(184, 216, 255, 0.2);
    border: 1px solid rgba(184, 216, 255, 1);
    margin: 0;
    min-width: 80px;
    height: 45px;
}
.history >>> .el-dialog__body {
    padding: 0 20px 30px 30px;
}
.tr1 {
    height: 41px;
}
.tr2 {
    height: 44px;
    background: rgba(184, 216, 255, 0.05);
}
#table {
    width: 100%;
    border-collapse: collapse;
}
#table td {
    border: 1px solid rgba(184, 216, 255, 1);
}
.tdItem {
    text-align: center;
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: rgba(102, 102, 102, 1);
    height: 40px;
    text-overflow: ellipsis;
    max-width: 200px;
}
.tableBox {
    min-height: 300px;
}
.history/deep/.el-dialog__body {
    max-height: 600px;
    overflow-y: scroll;
}
.progress {
    width: 100%;
    border: 1px solid rgba(184, 216, 255, 1);
    border-top: none;
    box-sizing: border-box;
    height: 60px;
    padding: 0 20px;
    display: flex;
    align-items: center;
    .progress-width {
      width: 300px;
    }
}
.progress/deep/.el-progress__text {
    // width: 50px;
    padding-left: 22px;
}
.tdItem1 {
    width: 140px;
    padding: 0 0 0 10px;
    text-align: left;

    box-sizing: border-box;
}
.el-progress {
    display: flex;
    align-items: center;
}
.handle-box /deep/.el-input--small .el-input__inner {
    height: 35px;
}
.progress/deep/.el-progress-bar {
    width: 339px;
}
.progress/deep/.el-progress__text {
    width: 100% !important;
}
.tdItem/deep/.el-progress-bar {
    width: 144px;
}
.history/deep/.el-dialog__body {
    padding-top: 35px !important;
    padding-bottom: 64px;
}
// 表格数据统计行
.table-data_statistic {
  width: 100%;
  height: 60px;
  line-height: 60px;
  border: 1px solid rgba(184, 216, 255, 1);
  border-top: none;
  box-sizing: border-box;
  ::v-deep .el-form-item--small.el-form-item {
    margin-bottom: 0;
  }
  ::v-deep .el-form-item__label {
    font-size: 16px;
    color: #000;
  }
  ::v-deep .el-form-item--small .el-form-item__content{
    line-height: 60px;
    font-size: 16px;
    color: #000;
  }
}
</style>
